package cc.aliza.lib.mongo.core.encoder;

import cc.aliza.lib.mongo.core.AlizaEntity;
import cc.aliza.lib.mongo.core.InternalDao;
import cc.aliza.lib.mongo.core.annotations.Default;
import cc.aliza.lib.mongo.core.annotations.Ref;
import cc.aliza.lib.mongo.core.cache.DaoCache;
import cc.aliza.lib.mongo.core.utils.FieldUtil;
import cc.aliza.lib.mongo.core.utils.ReferenceUtil;

import java.lang.reflect.Field;

/**
 * 『给时光以生命·给岁月以文明』
 *
 * @author Zhang Jing (byrdkm17@gmail.com).
 */
@SuppressWarnings("unchecked")
public class RefEncoder extends AbstractEncoder {

    private Ref ref;

    public RefEncoder(Object obj, Field field) {
        super(obj, field);
        ref = field.getAnnotation(Ref.class);
    }

    @Override
    public String getFieldName() {
        return getFieldRealName(ref.name());
    }

    @Override
    public Object encode() {
        AlizaEntity entity = (AlizaEntity) value;
        String refCascade = ref.cascade().toUpperCase();
        if (refCascade.contains(Default.CASCADE_CREATE) || refCascade.contains(Default.CASCADE_UPDATE)) {
            InternalDao dao = DaoCache.getInstance().get(FieldUtil.getRealType(field, entity));
            dao.save(entity);
        }
        return ReferenceUtil.toDBRef(entity);
    }
}
